package com.aidansmeaton.weightmanager;

import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.aidansmeaton.weightmanager.adapter.EmoticonAdapter;
import com.aidansmeaton.weightmanager.data.DatabaseHelper;
import com.aidansmeaton.weightmanager.util.ImageHelper;
import com.aidansmeaton.weightmanager.util.TimeFormatter;

/** The first activity in the app. */
public class DiaryMoodActivity extends ListActivity {
	
	private DatabaseHelper db;
	private Cursor c;
	
	private String datetime_today;
	private String date;
	private int selected_emoticon;
	
	private EditText commentBox;
	private ImageButton emoticonButton;
	private ImageView submitButton;
	
	ListAdapter a;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_mood);
        
        db = DatabaseHelper.getInstance(this);
        
        datetime_today = TimeFormatter.getDatetimeNow();
        date = getIntent().getStringExtra("Date");
        selected_emoticon = -1;
        
        commentBox = (EditText) findViewById(R.id.comment_box);
        emoticonButton= (ImageButton) findViewById(R.id.emoticon_button);
        submitButton = (ImageView) findViewById(R.id.submit_button);
        
        // don't allow to write in mood diary if date is not today
        if (!datetime_today.contains(date)){
        	commentBox.setEnabled(false);
        	emoticonButton.setEnabled(false);
        	submitButton.setEnabled(false);
        }
        
        c = db.getMoodLogs(date);
        Log.w("",""+c.getCount());
        setListAdapter(new MoodAdapter(this, c));
        
        getListView().setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	int mood_id = (int)(Integer) view.getTag();
				editMood(mood_id);
            }
		});
        
        // stop soft keyboard popping up automatically
        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        
	}
    
    protected void editMood(final int mood_id) {
    	
    	Cursor c = db.getMoodLog(mood_id);
    	c.moveToFirst();
    	int emoticon = c.getInt(DatabaseHelper.MOOD_LOG_EMOTICON);
    	String comment = c.getString(DatabaseHelper.MOOD_LOG_COMMENT);
    	final String date = c.getString(DatabaseHelper.MOOD_LOG_DATE);
    	
    	// initialise dialog
    	final Dialog d = new Dialog(this);
    	d.setTitle(getString(R.string.diary_mood_comment_hint));
    	d.setContentView(R.layout.dialog_edit_mood);
    	d.show();
    	
    	// force width to fill parent
    	LayoutParams params = d.getWindow().getAttributes();
        params.width = LayoutParams.FILL_PARENT; 
        d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
    	
        final EditText edit = (EditText) d.findViewById(R.id.comment_box);
        final Gallery gallery = (Gallery) d.findViewById(R.id.gallery);
        final Button save = (Button) d.findViewById(R.id.okay_button);
        final Button cancel = (Button) d.findViewById(R.id.cancel_button);
        final Button remove = (Button) d.findViewById(R.id.remove_button);
    	
    	edit.setText(comment);
        gallery.setAdapter(new EmoticonAdapter(this));
        gallery.setSelection( (emoticon==-1) ? (gallery.getCount()/2) : emoticon, true);
        
        remove.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				d.dismiss();
		    	db.removeMoodLog(mood_id);
				refreshListView();									
			}
        });
        
        save.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				d.dismiss();
		    	db.editMoodLog(mood_id, date, edit.getText().toString(), gallery.getSelectedItemPosition());
				refreshListView();				
			}
        });
        
        cancel.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				d.dismiss();			
			}
        });
		
	}

	/**
     *  Public callback method for when submit button clicked
     */
    public void submitClick(View v){
    	
    	// get info
    	datetime_today = TimeFormatter.getDatetimeNow();
    	String comment = retrieveComment();
    	
    	// input validation - then add new mood log to database
    	if (comment.equals("") && selected_emoticon == -1){
    		Toast.makeText(this, getString(R.string.diary_mood_warning), Toast.LENGTH_SHORT).show();
    		return;
    	}
    	db.addMoodLog(datetime_today, comment, selected_emoticon);
    	
    	// reset view
    	commentBox.setText("");
    	commentBox.setHint(getString(R.string.diary_mood_comment_hint));
        selected_emoticon = -1;
    	emoticonButton.setImageResource(ImageHelper.getEmoticon(selected_emoticon));
    	refreshListView();
    }
    
    /**
     *  Get comment from box, or "suggestion" if emoticon only, or nothing
     */
    private String retrieveComment() {
    	String comment = commentBox.getText().toString();
    	if (comment.equals("")) comment = commentBox.getHint().toString();
    	if (comment.equals(getString(R.string.diary_mood_comment_hint))) comment = "";
    	return comment;
	}

	/**
     *  Public callback method for when emoticon button clicked
     */
    public void emoticonClick(View v){
    	
    	// initialise dialog
    	final Dialog d = new Dialog(this);
    	d.setTitle(getString(R.string.diary_mood_comment_hint));
    	d.setContentView(R.layout.dialog_emoticons);
    	d.show();
    	
    	// force width to fill parent
    	LayoutParams params = d.getWindow().getAttributes(); 
        params.width = LayoutParams.FILL_PARENT; 
        d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
    	
    	Gallery gallery = (Gallery) d.findViewById(R.id.gallery);
        Button clearButton = (Button) d.findViewById(R.id.clear_button);

        gallery.setAdapter(new EmoticonAdapter(this));
        gallery.setSelection( (selected_emoticon==-1) ? (gallery.getCount()/2) : selected_emoticon, true);
        gallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position, long id) {
            	d.dismiss();
                selectEmoticon(position);
            }
        });
        
        clearButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				d.dismiss();
				selectEmoticon(-1);	// select empty emoticon
			}
        });
    	
    }
    
    protected void selectEmoticon(int position) {
    	selected_emoticon = position;
    	emoticonButton.setImageResource(ImageHelper.getEmoticon(selected_emoticon));
    	commentBox.setHint(ImageHelper.getAnnotationForEmoticon(selected_emoticon));
	}

	private void refreshListView(){
    	c.requery();
    	((MoodAdapter)getListView().getAdapter()).changeCursor(c);
    }
    
    private class MoodAdapter extends CursorAdapter {
		private LayoutInflater inflater;
		
		public MoodAdapter(Context context, Cursor cursor) {
			super(context, cursor);
			
			inflater = LayoutInflater.from(context);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			
			// Set ID tag
			view.setTag(cursor.getInt(DatabaseHelper.MOOD_LOG_ID));
						
			TextView comment = (TextView) view.findViewById(R.id.mood_comment);
			comment.setText(cursor.getString(DatabaseHelper.MOOD_LOG_COMMENT));
			
			TextView time = (TextView) view.findViewById(R.id.mood_time);
			time.setText(TimeFormatter.getTimeAsString(cursor.getString(DatabaseHelper.MOOD_LOG_DATE),false));
			
			ImageView emoticon = (ImageView) view.findViewById(R.id.mood_emoticon);
			emoticon.setImageResource(ImageHelper.getEmoticon(cursor.getInt(DatabaseHelper.MOOD_LOG_EMOTICON)));
			
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return inflater.inflate(R.layout.diary_mood_row, null);
		}
	}
	
}